﻿
namespace Patterns4Net.ArchitectureExplorer.ViewModels
{
    using System.Collections.ObjectModel;
    using Core;
    using System.ComponentModel.Composition;
    using System.Diagnostics.Contracts;
    using Caliburn.Micro;
    using Diagram;
    using Messages;

    [Export(typeof(DiagramBrowserViewModel))]
    public class DiagramBrowserViewModel : PropertyChangedBase, IHandle<DiagramUpdatedMessage>
    {
        private readonly IEventAggregator eventAggregator;

        private Diagram diagram;

        [ImportingConstructor]
        public DiagramBrowserViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            eventAggregator.Subscribe(this);
            this.Layers = new ObservableCollection<Layer>();
        }

        public ObservableCollection<Layer> Layers { get; private set; }

        public void SelectedItemChanged(object item)
        {
            Contract.Requires(item is DiagramElement);
            if (item != null && item is DiagramElement)
            {
                this.eventAggregator.Publish(new SelectDiagramElementMessage((DiagramElement)item));
            }

            // an item may be also a special object indicating that the TreeView has been cleared.
        }
        
        public void ItemDoubleClick(object item)
        {
            Contract.Requires(item is DiagramElement);
            if (item != null && item is DiagramElement)
            {
                this.eventAggregator.Publish(new ZoomToDiagramElementMessage((DiagramElement)item));
            }
        }

        public void Handle(DiagramUpdatedMessage message)
        {
            this.diagram = message.Diagram;
            this.Layers.Clear();
            if (this.diagram != null)
            {
                this.diagram.Layers.ForEach(this.Layers.Add);
            }
        }
    }
}
